// 手写服务器
const http = require('http')
const fs = require('fs')
const { createProxyMiddleware } = require('http-proxy-middleware')
// const { u } = require('tar')
//keyword数据地址
let fn = createProxyMiddleware('/api/HotKeyWord', {
    target: 'http://you.163.com/xhr/search/queryHotKeyWord.json',
    changeOrigin: true,
    pathRewrite: {
        '/api/HotKeyWord': ''
    }
})
//indexNav数据地址
let fn1 = createProxyMiddleware('/api/globalinfo', {
    target: 'http://you.163.com/xhr/globalinfo//queryTop.json',
    changeOrigin: true,
    pathRewrite: {
        '/api/globalinfo': ''
    }
})
//新品首发数据地址
let fn2 = createProxyMiddleware('/api/getNewItem', {
    target: 'http://you.163.com/xhr/item/getNewItem.json',
    changeOrigin: true,
    pathRewrite: {
        '/api/getNewItem': ''
    }
})
//新品列表数据获取
let fn3 = createProxyMiddleware('/api/getMoreNewItem', {
    target: 'http://you.163.com/xhr/item/getMoreNewItem.json',
    changeOrigin: true,
    pathRewrite: {
        '/api/getMoreNewItem': ''
    }
})
//新品页预售
let fn4 = createProxyMiddleware('/api/getPreNewItem', {
    target: 'http://you.163.com/xhr/item/getPreNewItemWithScreeningRoom.json',
    changeOrigin: true,
    pathRewrite: {
        '/api/getPreNewItem': ''
    }
})
//可能喜欢列表
let fn5 = createProxyMiddleware('/api/likeItem', {
    target: 'http://you.163.com/xhr/item/rcmd.json',
    changeOrigin: true,
    pathRewrite: {
        '/api/likeItem': ''
    }
})
//24小时热销榜
let fn6 = createProxyMiddleware('/api/hotsellItem', {
    target: 'http://you.163.com/xhr/item/hotsellItem.json',
    changeOrigin: true,
    pathRewrite: {
        '/api/hotsellItem': ''
    }
})
//搜索框
let fn7 = createProxyMiddleware('/api/search', {
    target: 'http://you.163.com/xhr/search/search.json',
    changeOrigin: true,
    pathRewrite: {
        '/api/search': ''
    }
})
let fn8 = createProxyMiddleware('/api/keyword', {
    target: 'http://you.163.com/xhr/search/searchAutoComplete.json',
    changeOrigin: true,
    pathRewrite: {
        '/api/keyword': ''
    }
})
http.createServer((request, response) => {
    //接口
    if (request.url.startsWith('/api')) {
        //注册
        if (request.url === '/api/register') {
            //将注册页面的数据转换为字符串
            let str = '';
            request.on('data', chunk => {
                str += chunk.toString()
            })
            request.on('end', () => {
                //将数据转换为对象
                let arr = str.split('&')
                let obj = {}
                arr.forEach(item => {
                    let brr = item.split('=')
                    obj[brr[0]] = brr[1]
                })
                //读取json文件(buffer)，转换为字符串
                let data = fs.readFileSync('./project/src/json/data.json')
                data = data.toString()
                let pbj = {
                    code: 0,
                    msg: '用户名被占用了'
                }
                //json文件中没有数据
                if (data === '') {
                    data = []
                    data.push(obj)
                    fs.writeFileSync('./project/src/json/data.json', JSON.stringify(data))
                    pbj = {
                        code: 1,
                        msg: '注册成功,请登录'
                    }
                    response.end(JSON.stringify(pbj))
                    return false
                }
                //json文件中有数据
                data = JSON.parse(data)
                //判断此用户是否存在
                let index = data.findIndex(item => item.username === obj.username)
                //不存在，加入
                if (index < 0) {
                    data.push(obj)
                    data = JSON.stringify(data)
                    fs.writeFileSync('./project/src/json/data.json', data)
                    pbj = {
                        code: 1,
                        msg: '注册成功'
                    }
                    response.end(JSON.stringify(pbj))
                }
                // 找到数据了 - 用户名被占用了
                response.end(JSON.stringify(pbj))
            })
        }
        //登录
        else if (request.url === '/api/login') {
            //将登录页面的数据转换为字符串
            let str = '';
            request.on('data', chunk => {
                str += chunk.toString()
            })
            request.on('end', () => {
                //将数据转换为对象
                let arr = str.split('&')
                let obj = {}
                arr.forEach(item => {
                    let brr = item.split('=')
                    obj[brr[0]] = brr[1]
                })
                //读取json文件(buffer)，转换为字符串
                let data = fs.readFileSync('./project/src/json/data.json')
                data = data.toString()
                data = JSON.parse(data)

                let index = data.findIndex(item => item.username === obj.username)
                let pbj = {
                    code: 3,
                    msg: '用户名不存在，请先注册'
                }
                if (index < 0) {
                    response.end(JSON.stringify(pbj))
                } else {
                    let index1 = data.findIndex(item => item.username === obj.username && item.password === obj.password)
                    let userInfo = data.find(item => item.username === obj.username)
                    delete userInfo.password
                    userInfo = JSON.stringify(userInfo)
                    if (index1 < 0) {
                        pbj = {
                            code: 2,
                            msg: '登陆失败,用户名或密码错误'
                        }
                        response.end(JSON.stringify(pbj))
                    }
                    pbj = {
                        code: 1,
                        msg: '登录成功',
                        userInfo: userInfo
                    }
                }
                response.end(JSON.stringify(pbj))
            })
        }
        //个人信息
        else if (request.url === '/api/info') {
            let str = '';
            request.on('data', chunk => {
                str += chunk.toString()
            })
            request.on('end', () => {
                let arr = str.split('&')
                let obj = {}
                arr.forEach(item => {
                    let brr = item.split('=')
                    obj[brr[0]] = brr[1]
                })
                let data = fs.readFileSync('./project/src/json/data.json')
                data = data.toString()
                data = JSON.parse(data)
                let pbj = {
                    code: 1,
                    msg: '修改个人信息成功，请重新登陆'
                }
                let item = data.find(item => { return item.username === obj.username })
                item.nickname = obj.nickname;
                item.sex = obj.sex;
                item.age = obj.age;
                item.identity = obj.identity;
                fs.writeFileSync('./project/src/json/data.json', JSON.stringify(data))
                response.end(JSON.stringify(pbj))
            })

        }
        //修改密码
        else if (request.url === '/api/changepwd') {
            let str = '';
            request.on('data', chunk => {
                str += chunk.toString()
            })
            request.on('end', () => {
                let arr = str.split('&')
                let obj = {}
                arr.forEach(item => {
                    let brr = item.split('=')
                    obj[brr[0]] = brr[1]
                })
                let data = fs.readFileSync('./project/src/json/data.json')
                data = data.toString()
                data = JSON.parse(data)
                let pbj = {
                    code: 1,
                    msg: '修改密码成功，请重新登录'
                }
                let index = data.findIndex(item => item.password === obj.oldPassword && item.username === obj.username)

                //密码输入不正确
                if (index < 0) {
                    pbj = {
                        code: 0,
                        msg: '旧密码输入错误，请重新输入'
                    }
                    response.end(JSON.stringify(pbj))
                }
                let item = data.find(item => { return item.username === obj.username })
                item.password = obj.newPassword
                fs.writeFileSync('./project/src/json/data.json', JSON.stringify(data))
                response.end(JSON.stringify(pbj))
            })
        }
        //发送ajax
        else if (request.url.includes('/api/HotKeyWord')) {
            fn(request, response)
        } 
        else if (request.url.includes('/api/globalinfo')) {
            fn1(request, response)
        } 
        else if (request.url.includes('/api/getNewItem')) {
            fn2(request, response)
        } 
        else if (request.url.includes('/api/getMoreNewItem')) {
            fn3(request, response)
        } 
        else if (request.url.includes('/api/getPreNewItem')) {
            fn4(request, response)
        } 
        else if (request.url.includes('/api/likeItem')) {
            fn5(request, response)
        } 
        else if (request.url.includes('/api/hotsellItem')) {
            fn6(request, response)
        } 
        else if (request.url.includes('/api/search')) {
            fn7(request, response)
        } 
        else if (request.url.includes('/api/keyword')) {
            fn8(request, response)
        }
    }
    else if (request.url === '/node_modules/jquery/dist/jquery.js') {
        let data = fs.readFileSync('./project/node_modules/jquery/dist/jquery.js')
        response.end(data)
    }
    else{
        if (request.url === '/') {
            request.url = '/index.html'
        }
        else if (request.url === '/js/layer/theme/default/layer.css?v=3.5.1') {
            request.url = '/js/layer/theme/default/layer.css'
        } else if (request.url.includes('.woff') || request.url.includes('.ttf')) {
            request.url = request.url.split('?')[0]
        } else if (request.url.includes('?')) {
            let index = request.url.indexOf('?')
            request.url = request.url.slice(0, index)
        }
        let data = fs.readFileSync('./project/dist' + request.url)
        response.end(data)
    }
}).listen(29999)